package com.study.www.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipDownloadUtils {

    private static final Logger log= LoggerFactory.getLogger(ZipDownloadUtils.class);
/**
 *
 *ZipDownloadUtils.downloadFolder(Arrays.asList("D:\\class\\v1\\1.mp4","D:\\class\\v1\\2.mp4","D:\\class\\v2\\3.mp4","D:\\class\\v2\\4.mp4"),"test.zip",response);
 *
 */
     public static void downloadFolder(List<String> sourceFilePaths, String zipName, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(zipName,"UTF-8")  + "\"");
        ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
        InputStream inputStream =null;
        try{
            for (String file : sourceFilePaths) {
                File fileTmp=new File(file);
                if(!fileTmp.exists()){
                    log.error("未找到文件：{}",file);
                    throw new IOException("未找到文件："+file);
                }
                ZipEntry entry = new ZipEntry(file);
                zipOut.putNextEntry(entry);
                //将文件流写入文件中
                inputStream=new FileInputStream(file);

                byte[] buffer = new byte[10240];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    zipOut.write(buffer, 0, len);
                }
            }
        } catch (IOException e) {
            log.error("文件压缩下载异常：",e.getMessage());
            e.printStackTrace();
        }finally {
            if(zipOut!=null){
                zipOut.closeEntry();
                zipOut.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
        }
    }

}